<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 2019-07-14
 * Time: 10:49
 */

namespace app\api\service;


use app\common\facade\Token;
use app\common\model\User;
use app\common\service\WechatMini;
use library\File;
use library\tools\Data;
use think\facade\Log;
use WeChat\Contracts\Tools;

class WechatMiniService
{
    /**
     * 小程序code授权
     * @param $code 小程序code
     * @return array|bool 返回token
     */
    public static function login($code)
    {
        $mini = WechatMini::WeMiniCrypt();
        $res = $mini->session($code);
        if (empty($res['session_key'])) {
            return false;
        } else {
            $openid = $res['openid'];
            $unionid = $res['unionid'] ? $res['unionid'] : '';
            $user = User::where('openid', $openid)->whereOr(function ($q) use ($unionid) {
                $q->where('unionid', $unionid)->whereNotNull('unionid')->where('unionid', '<>', '');
            })->find();
            if ($user) {
                $user->unionid = $unionid;
                $user->openid = $openid;
                $user->save();
            } else {
                $user = User::create([
                    'unionid' => $unionid,
                    'openid' => $openid,
                ]);
            }
            $user['session_key'] = $res['session_key'];
            $tokenArr = Token::encode($user->getData());
            return $tokenArr;
        }
    }

    /**
     * 小程序授权首次更新用户信息
     * @param $iv
     * @param $encryptedData
     * @return bool
     */
    public static function updateInfo($iv, $iv2, $encryptedData, $encryptedData2)
    {
        $mini = WechatMini::WeMiniCrypt();
        $res = $mini->decode($iv, Token::getVar('session_key'), $encryptedData);

        $mini = WechatMini::WeMiniCrypt();
        $res2 = $mini->decode($iv2, Token::getVar('session_key'), $encryptedData2);
        if ($res) {
            User::update([
                'id' => Token::id(),
                'nickname' => $res['nickName'],
                'headimg' => $res['avatarUrl'],
                'unionid' => $res['unionId'],
                'country' => $res['country'],
                'city' => $res['city'],
                'province' => $res['province'],
                //'phone' => $res2['phoneNumber']
            ]);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取微信手机号
     * @Author: rocky
     * 2019/7/20 15:56
     * @param $iv
     * @param $encryptedData
     * @return mixed
     */
    public static function getPhone($iv, $encryptedData)
    {
        $mini = WechatMini::WeMiniCrypt();
        $res = $mini->decode($iv, Token::getVar('session_key'), $encryptedData);
        if ($res) {
            return $res['phoneNumber'];
        } else {
            return false;
        }
    }

    /**
     * 微信支付
     * @Author: rocky
     * 2019/7/22 15:33
     * @param $openid openid
     * @param $title 下单标题
     * @param $order_sn 订单号
     * @param $total  总价
     * @param $notify_url  回调地址
     * @return mixed
     */
    public static function pay($openid, $title, $order_sn, $total, $notify_url)
    {
        $wechatPay = WechatMini::WePayOrder();
        $res = $wechatPay->create([
            'body' => $title,
            'out_trade_no' => $order_sn,
            'total_fee' => $total * 100,
            'spbill_create_ip' => request()->ip(),
            'notify_url' => $notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ]);
        $wechatPayConfig = $wechatPay->jsapiParams($res['prepay_id']);
        return $wechatPayConfig;
    }

    /**
     * 微信申请退款
     * @Author: rocky
     * 2019/9/2 11:11
     * @param $transaction_id 微信订单号
     * @param $order_sn 订单号
     * @param $total_fee 订单金额
     * @param $refund_fee 退款金额
     * @return bool
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public static function refund($transaction_id,$order_sn,$total_fee,$refund_fee){
        $options = [
            'transaction_id' => $transaction_id,
            'out_refund_no' =>$order_sn,
            'total_fee' => $total_fee* 100,
            'refund_fee' => $refund_fee * 100,
        ];
        $res = WechatMini::WePayRefund()->create($options);
        if ($res['result_code'] == 'SUCCESS') {
            return true;
        }else{
            return $res['err_code_des'];
        }
    }
    /**
     * 微信企业付款
     * @Author: rocky
     * 2019/9/2 11:01
     * @param $openid openid
     * @param $money 打款金额
     * @param $desc 打款描述
     * @return bool
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public static function transfersPay($openid, $money, $desc)
    {
        $options = [
            'partner_trade_no' => time(),
            'openid' => $openid,
            'check_name' => 'NO_CHECK',
            'amount' => $money * 100,
            'desc' => $desc,
            'spbill_create_ip' => request()->ip(),
        ];
        $result = WechatMini::WePayTransfers()->create($options);
        if ($result['result_code'] == 'SUCCESS') {
            return true;
        } else {
            return $result['err_code_des'];
        }
    }
    /**
     * 小程序模板消息发送
     * @Author: rocky
     * 2020/2/25 16:39
     * @param $template_id 模板id
     * @param $open_id 微信open_id
     * @param $form_id 微信小程序获取的form_id
     * @param $content 发送内容  格式：标题1&标题1 或数组 ['标题1','标题2']
     * @param string $emphasis_keyword 模板需要放大的关键词，不填则默认无放大
     * @param string $page 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     * @return bool
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public static function sendTemplate($template_id,$open_id,$form_id,$content,$emphasis_keyword='',$page ='pages/index/index',$color='#5d5d58'){
        if(is_array($content)){
            foreach($content as $key => $value){
                $data['keyword'.($key+1)]['value'] = $value;
                $data['keyword'.($key+1)]['color'] = $color;
            }
        }else{
            foreach(explode('&',$content) as $key => $value){
                $data['keyword'.($key+1)]['value'] = $value;
                $data['keyword'.($key+1)]['color'] = $color;
            }
        }
        $postData = [
            'touser' => $open_id,
            'template_id' => $template_id,
            'page' => $page,
            'form_id' => $form_id,
            'data' => $data,
            'emphasis_keyword' => $emphasis_keyword
        ];
        if($form_id){
            $result = WechatMini::WeMiniTemplate()->send($postData);
            if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){
                return true;
            }
        }
        return false;
    }
}